package com.tlb.ejb;


import com.tlb.dto.Poster;
import com.tlb.dto.Moniker;
import com.tlb.dto.FlaggedThread;
import java.util.*;
import javax.persistence.*;

public class PosterDAO {

    private static com.tlb.web.Util util = com.tlb.web.Util.getUtil();
    public PosterDAO() {
    }

    public void updatePassword(int posterId, String rawPassword) {
        try {
            EntityManager em = util.getPersistenceFactory().createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();

            em.createQuery(
                    "update Poster p set password = password(concat(salt, :rawPassword)) where posterId = :posterId ").setParameter("posterId", posterId).setParameter("rawPassword", rawPassword).executeUpdate();

            tx.commit();
            em.close();

        } catch (Exception e) {
            System.err.println("Error updating password: " + posterId + ", " + rawPassword);
            e.printStackTrace();
        }
    }

    
    public void updateFilter(int posterId, boolean spam, boolean nsfw) {
        try {
            EntityManager em = util.getPersistenceFactory().createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();

            em.createQuery(
                    "update Poster p set spam = :spam, nsfw = :nsfw where posterId = :posterId ")
                    .setParameter("posterId", posterId)
                    .setParameter("spam", spam)
                    .setParameter("nsfw", nsfw)
                    .executeUpdate();

            tx.commit();
            em.close();

        } catch (Exception e) {
            System.err.println("Error updating filter: " + posterId + ", spam: " + spam + ", nsfw: " + nsfw);
            e.printStackTrace();
        }
    }
    
    public void updateInlineReply(int posterId, int inlineReply) {
        try {
            EntityManager em = util.getPersistenceFactory().createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();

            em.createQuery(
                    "update Poster p set inlineReply = :inlineReply where posterId = :posterId ")
                    .setParameter("inlineReply", inlineReply)
                    .setParameter("posterId", posterId)
                    .executeUpdate();

            tx.commit();
            em.close();

        } catch (Exception e) {
            System.err.println("Error updating inlineReply: " + posterId + ", inlineReply: " + inlineReply);
            e.printStackTrace();
        }
    }
    
    public boolean validateLogin(String userName, String rawPassword) {
        try {
            EntityManager em = util.getPersistenceFactory().createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();

            Poster p = (Poster) (em.createQuery(
                    "select p from Poster p where userName = :user and password = password(concat(salt, :rawPassword))')").setParameter("user", userName).setParameter("rawPassword", rawPassword).getSingleResult());

            tx.commit();
            em.close();

            if (p != null && p.getPosterId() > 0) {
                return true;
            }

        } catch (Exception e) {
            System.err.println("Error validating login for: " + userName + ", " + rawPassword);
            e.printStackTrace();
        }

        return false;
    }

    public Poster getPoster(String userName, String rawPassword) {

        if (userName == null || userName.trim().equals("")) {
            return null;
        }

        userName = userName.trim();
        userName = userName.replace("^\\s+", "");

        try {
            EntityManager em = util.getPersistenceFactory().createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();

            Poster p = null;
            try {
                p = (Poster) (em.createQuery(
                        "select p from Poster p where userName = :user and password = password(concat(salt, :rawPassword))").setParameter("user", userName).setParameter("rawPassword", rawPassword).getSingleResult());
            } catch (Exception e) {
                System.out.println("Exception in getPoster(String,String): " + e.getMessage());
            }

            tx.commit();
            em.close();

            if (p != null && p.getPosterId() > 0) {
                return p;
            }

        } catch (NoResultException e) {
            System.out.println("Poster.getPoster(String, String) - no result for: " + userName + "/" + rawPassword);
            e.printStackTrace();
        }

        return null;
    }
    
    
    public Poster getPosterByUUID(String uuid) {

        if (uuid == null || uuid.trim().equals(""))
            return null;


        try {
            EntityManager em = util.getPersistenceFactory().createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();
            Poster p = null;
            try {
                p = (Poster) (em.createNativeQuery(
            		"select \n" +
            		"  p.posterId, p.userName, null as 'password', p.active, p.primaryMonikerId, p.userLevelId, p.nsfw, p.spam, 0 as salt, p.inlineReply \n" +
            		"from \n" +
            		"  poster p, \n" +
            		"  activesession actS \n" +
            		"where \n" +
            		"  p.posterid = actS.posterId \n" +
            		"  and actS.uuid = :uuid \n" +
            		"  and actS.goodUntilDate > now() \n",
            		Poster.class
               )
               .setParameter("uuid", uuid)
               .getSingleResult());
            } catch (javax.persistence.NoResultException e) {
                System.out.println("Poster.getPosterByUUID(String) - no result for: " + uuid);
            }
            tx.commit();
            em.close();

            return p;
        } catch (Exception e) {
            System.err.println("Error getting posterbyuuid(creds): " + uuid);
            e.printStackTrace();
        }

        return null;
    }    
    

    
    public Poster getPoster(String userName) {

        if (userName == null || userName.trim().equals("")) {
            return null;
        }

        userName = userName.trim();
        userName = userName.replace("^\\s+", "");


        try {
            EntityManager em = util.getPersistenceFactory().createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();
            Poster p = null;
            try {
                p = (Poster) (em.createQuery(
                        "select p from Poster p where userName = :user").setParameter("user", userName).getSingleResult());
            } catch (javax.persistence.NoResultException e) {
                System.out.println("Poster.getPoster(String) - no result for: " + userName);
            }
            tx.commit();
            em.close();

            if (p != null && p.getPosterId() > 0) {
                return p;
            }

        } catch (Exception e) {
            System.err.println("Error getting poster(creds): " + userName);
            e.printStackTrace();
        }

        return null;
    }
     
    public Poster getPoster(int posterId) {
        Poster p = null;
        
        try {
            EntityManager em = util.getPersistenceFactory().createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();

            p = (Poster) (em.find(Poster.class, new Integer(posterId)));

            tx.commit();
            em.close();

        } catch (NoResultException nre) {
        } catch (Exception e) {            
            System.err.println("Error getting Poster(id): " + posterId);
            e.printStackTrace();
        }

        return p;
    }
	
    
    
    
    
    public void savePoster(Poster p, boolean newUser) {
        try {
            EntityManager em = util.getPersistenceFactory().createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();

            if (newUser) {
                em.persist(p);
            } else {
                em.merge(p);
            }

            tx.commit();
            em.close();


        } catch (Exception e) {
            System.err.println("Error saving Poster: " + e.getMessage());
            e.printStackTrace();
        }

    }

    public void updatePrimaryMonikerId(Poster p, Moniker newPrimMoniker) {
        try {
            EntityManager em = util.getPersistenceFactory().createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();

            if (p == null || newPrimMoniker == null) {
                System.out.println("updatePrimaryMonikerId error A");
                return;
            }

            if (p.getPosterId() != newPrimMoniker.getPoste().getPosterId() || p.getPrimaryMoniker().getMonikerId() == newPrimMoniker.getMonikerId()) {
                return;
            }


            Moniker dbMoniker = new MonikerDAO().getMoniker(newPrimMoniker.getMonikerId());
            if (dbMoniker.getPoste().getPosterId() != p.getPosterId()) {
                System.out.println("updatePrimaryMonikerId error B");
                return;
            }




            em.createNativeQuery("update poster p set primaryMonikerId = :monikerId where posterId = :posterId").setParameter("monikerId", dbMoniker.getMonikerId()).setParameter("posterId", p.getPosterId()).executeUpdate();



            tx.commit();
            em.close();


        } catch (Exception e) {
            System.err.println("Error update Poster set primary moniker: " + e.getMessage());
            e.printStackTrace();
        }

    }
    
    
    
    
    
    
    
    
    
    
    
    
    public List<FlaggedThread> getFlaggedThreads(int posterId) {

        List<FlaggedThread> threads = null;

        try {
            EntityManager em = util.getPersistenceFactory().createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();

            try {
                threads = (List<FlaggedThread>)(em.createNativeQuery(
                    "select x.threadId, pc.title, fc.flagName, pf.flagDate \n" +
                    "from \n" +
                    "  ( \n" +
                    "    select p.threadId, max(pf.postFlagId) as postFlagId \n" +
                    "    from \n" +
                    "      postflag pf, \n" +
                    "      post p \n" +
                    "    where \n" +
                    "      pf.flagId in (1,2) \n" +
                    "      and pf.posterId = :posterId \n" +
                    "      and pf.postId = p.postId \n" +
                    "    group by p.threadId \n" +
                    "  ) as x, \n" +
                    "  postcontent pc, \n" +
                    "  flagcodes fc, \n" +
                    "  postflag pf \n" +
                    "where \n" +
                    "  x.threadId = pc.postId \n" +
                    "  and x.postFlagId = pf.postFlagId \n" +
                    "  and pf.flagId = fc.flagId \n" +
                    "order by pf.flagDate desc \n", FlaggedThread.class
                ).setParameter("posterId", posterId).getResultList());
            
            
            
            } catch (Exception e) {
                System.out.println("Exception in getFlaggedThreads(" + posterId + "): " + e.getMessage());
                e.printStackTrace();
            }

            tx.commit();
            em.close();


        } catch (NoResultException e) {
        }

        
        
        
        return threads;
    }    
    
}
